package com.xiaoxiao.springbootstudy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxiao.springbootstudy.pojo.RoleMenu;
import com.xiaoxiao.springbootstudy.service.RoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
public class RoleMenuController {
    @Autowired
    private RoleMenuService roleMenuService;

    @PostMapping("/grantRoleMenus")
    public Map<String, Object> grantRoleMenus(@RequestBody Integer[] roleIds) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 400);
        map.put("msg", "操作失败");

        try {
            Integer roleId = roleIds[0];
            List<RoleMenu> list = new ArrayList<>();

            for (int x = 1; x < roleIds.length; x++) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRid(roleId);
                roleMenu.setMid(roleIds[x]);
                list.add(roleMenu);
            }
            //创建对象，封装删除的where条件
            QueryWrapper<RoleMenu> cond = new QueryWrapper<>();
            cond.eq("rid", roleId);
            //断开该角色和菜单的关系，执行删除
            roleMenuService.remove(cond);

            roleMenuService.saveBatch(list);
            map.put("code", 200);
            map.put("msg", "角色授权成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    /*处理根据角色id查询所有菜单id集合*/
    @GetMapping("/loadRoleMid/{rid}")
    public List<Integer> loadRoleMid(@PathVariable Integer rid) {

//        QueryWrapper<RoleMenu> wrapper = new QueryWrapper<>();
//        wrapper.eq("rid", rid);
//        wrapper.select("mid");
//        List<Integer> result = roleMenuService.listObjs(wrapper);
        return roleMenuService.queryRoleMidsListService(rid);
    }
}
